<?php
namespace app\user\model;

use app\common\model\Applet as AppletModel;
use think\facade\Db;

/**
 * 小程序模型
 */
class Applet extends AppletModel
{
    /**
     * 续费
     */
    public function upgrade($data, $template)
    {
        $user = User::getUser(['user_id' => $this->user_id]);//获取商户详情
        $pay = 0;//支付费用
        $agent_price = 0;//代理费用
        //计算费用
        if($this->shop_mode['value']==10){
            //单商户
            $pay = $template['renew_single'][$data['year']-1];
            $agent_price = $template['single_price']*$data['year'];
        }
        if($this->shop_mode['value']==20){
            //多商户
            $pay = $template['renew_many'][$data['year']-1];
            $agent_price = $template['many_price']*$data['year'];
        }
        $day = $data['year']*3600*24*365;//计算到期时间
        $money = $user['money']-$pay;//计算扣除后的余额
         // 开启事务
        Db::startTrans();
        try {
            $order_list = [];
            array_push($order_list,[
                'user_type' => 20,
                'action' => 40,//消费
                'order_no' => order_no(),
                'money' => $pay,
                'remark' => '小程序续费',
                'user_id' => $this->user_id
            ]);
            //扣除余额
            $user->money = ['dec',$pay];
            $user->save();
            //代理分账
            if($this->agent_id > 0){
                //代理分红
                $agent = User::getUser(['user_id' => $this->agent_id]);
                $agent->money = ['inc',$pay-$agent_price];
                $agent->save();
                array_push($order_list,[
                    'user_type' => 20,
                    'action' => 50,//分红
                    'order_no' => order_no(),
                    'money' => $pay-$agent_price,
                    'remark' => '续费分账',
                    'user_id' => $this->agent_id
                ]);                     
            }
            //添加流水记录
            $model = new Record;
            $model->saveAll($order_list);
            $this->expire_time = ['inc',$day];
            $this->save();
            //账户资金变动提醒
            sand_account_change_msg('小程序模板续费',$pay,$money,$this->user_id);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }
    

}